import {httpSuccessPost} from '@/utils/ajax'

function imageCompress(file) {
  return new Promise((resolve, reject) => {
    if (file.type === 'image/gif') { // 动态图canvas 绘图后会不动
      resolve(file)
    }
    try {
      const reader = new FileReader()
      const img = new Image()
      reader.readAsDataURL(file)
      reader.onload = function() {
        img.src = this.result
      }
      img.onload = () => {
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')
        canvas.width = img.width
        canvas.height = img.height
        ctx.drawImage(img, 0, 0)
        canvas.toBlob(function(blob) {
          resolve(blob)
        }, file.type, 0.95)
      }
    } catch (err) {
      resolve(file)
    }
  })
}

export default function upload(option) {
  const action = option.action

  const formData = new FormData()

  if (option.data) {
    Object.keys(option.data).forEach(key => {
      formData.append(key, option.data[key])
    })
  }
  // 设置header头
  let config = {
    headers: option.headers || {}
  }
  // 携带凭证
  if (option.withCredentials) {
    config.withCredentials = true
  }
  // 图片压缩
  return imageCompress(option.file).then(file => {
    formData.append(option.filename, file, option.file.name)
    // 处理进度
    /* config.onUploadProgress = (progressEvent) => {
      if (progressEvent.total > 0) {
        progressEvent.percent = progressEvent.loaded / progressEvent.total * 100
      }
      option.onProgress(progressEvent)
    } */
    return httpSuccessPost(action, formData, {}, config).then(response => {
      option.onSuccess(response)
      return response
    }).catch(err => {
      option.onError(err)
    })
  })
}
